<?php

declare(strict_types=1);

namespace App\Middleware\Auth;

use Hyperf\Contract\SessionInterface;
use Hyperf\Logger\LoggerFactory;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Log\LoggerInterface;

class PermissionMiddleware implements MiddlewareInterface
{
    protected SessionInterface $session;

    protected ContainerInterface $container;

    protected RequestInterface $request;

    protected HttpResponse $response;

    protected LoggerInterface $logger;


    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request, SessionInterface $session, LoggerFactory $loggerFactory)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
        $this->session = $session;
        $this->logger = $loggerFactory->get('log', 'default');

    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $uid = $this->session->get('user_id');
        if (!$uid) {
            //未登录
            $this->logger->error('未登录');
            return $this->response->redirect('/login');
        } else {
            return $handler->handle($request);
        }
    }
}